# coding=utf-8
from django.shortcuts import render, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from qa.models import qaWatch, qClass
# from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from qa.serializers import qaWatchSerializer, userSerializer, qClassSerializer
from django.contrib import auth
from django.template import RequestContext
from django import forms
import uuid
from django.contrib.auth.models import User
from qa import models
import time


# class sc365NewsViewSet(viewsets.ModelViewSet):
#     """
#     API端：新闻列表
#     """
#     queryset = sc365News.objects.all()
#     serializer_class = sc365NewsSerializer
class BackUpText(APIView):
    """
    API端：无法修复(备注)
    """

    def get(self, request, *args, **kwargs):
        if request.method == "GET":
            id = request.GET['id']
            q_backup = request.GET['q_backUp']
            a_user = request.GET['a_user']
            q_status = 4
            models.qaWatch.objects.filter(id=id).update(a_user=a_user, q_backUp=q_backup, q_status=q_status)
            return Response({'status': 'ok', 'message': '修改成功！'})
        else:
            return Response({'status': 'error', 'message': '修改失败！'})


class ConfirmQ(APIView):
    """
    API端：测试确认问题通过
    """

    def get(self, request, *args, **kwargs):
        if request.method == "GET":
            id = request.GET['q_id']
            q_checkOut = request.GET['q_checkOut']
            models.qaWatch.objects.filter(id=id).update(q_checkOut=q_checkOut)
            return Response({'status': 'ok', 'message': '修改成功！'})
        else:
            return Response({'status': 'error', 'message': '修改失败！'})


class qClassList(APIView):
    """
    API端：查询所有问题分类
    """

    def get(self, request, *args, **kwargs):
        bl_tab = qClass.objects.all().order_by('-pk')
        res_data = qClassSerializer(bl_tab, many=True).data
        return Response(res_data)


class qaWatchList(APIView):
    """
    API端：查询所有问题列表
    """

    def get(self, request, *args, **kwargs):
        bl_tab = qaWatch.objects.all().order_by('-pk')
        res_data = qaWatchSerializer(bl_tab, many=True).data
        return Response(res_data)


class addClassList(APIView):
    """
    API端：添加分类
    """

    def get(self, request, *args, **kwargs):
        if request.method == "GET":
            q_class = request.GET['q_class']
            # q_class = qClass.objects.get(id=getClass)
            models.qClass.objects.create(q_class=q_class)
            return Response({'status': 'ok', 'message': '添加成功！'})
        else:
            return Response({'status': 'error', 'message': '添加失败！'})


class addList(APIView):
    """
    API端：添加问题
    """

    def get(self, request, *args, **kwargs):
        if request.method == "GET":
            q_user = request.GET['q_user']
            q_timer = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            q_content = request.GET['q_content']
            q_level = request.GET['q_level']
            q_status = 0
            getClass = request.GET['q_class']
            q_class = qClass.objects.get(id=getClass)
            models.qaWatch.objects.create(q_user=q_user, q_timer=q_timer, q_content=q_content, q_level=q_level,
                                          q_status=q_status, q_class=q_class)
            return Response({'status': 'ok', 'message': '添加成功！'})
        else:
            return Response({'status': 'error', 'message': '添加失败！'})


class removeList(APIView):
    """
    API端：删除问题
    """

    def get(self, request, *args, **kwargs):
        if request.method == "GET":
            id = request.GET['q_id']
            models.qaWatch.objects.filter(id=id).delete()
            return Response({'status': 'ok', 'message': '删除成功！'})
        else:
            return Response({'status': 'error', 'message': '删除失败！'})


class changeQ(APIView):
    """
    API端：修改问题状态(前端)
    """

    def post(self, request, *args, **kwargs):
        if request.method == "POST":
            id = request.POST['id']
            a_user = request.POST['a_user']
            a_timer = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            q_status = request.POST['q_status']
            q_checkout = 0
            models.qaWatch.objects.filter(id=id).update(a_user=a_user, a_timer=a_timer,
                                                        q_status=q_status, q_checkOut=q_checkout)
            return Response({'status': 'ok', 'message': '修改成功！'})
        else:
            return Response({'status': 'error', 'message': '添加失败！'})


# Create your views here.
def index(request):
    return render(request, 'qa/index.html')


class login(APIView):
    def post(self, request, *args, **kwargs):
        if request.method == "POST":
            uf = UserFormLogin(request.POST)
            if uf.is_valid():
                # 获取表单信息
                username = uf.cleaned_data['username']
                password = uf.cleaned_data['password']
                getUser = User.objects.filter(username=username)
                userResult = auth.authenticate(username=username, password=password)
                # pdb.set_trace()
                if (len(getUser) > 0):
                    if (userResult):
                        # users = User.objects.get(username=username)'user': users
                        # print(User.objects.filter(username=username))
                        # print(auth.authenticate(username=username, password=password))
                        res_data = userSerializer(getUser, many=True).data
                        return Response({'status': 'ok', 'message': '登录成功！', 'username': res_data})
                    else:
                        return Response({'status': 'error', 'message': '密码错误！'})
                else:
                    return Response({'status': 'error', 'message': '该用户不存在！'})
        else:
            return Response({'status': 'error', 'message': '该用户不存在！'})

        return render_to_response("userlogin.html", {'uf': uf})


class checkLevel(APIView):
    """
     API端：用户身份识别
    """

    def post(self, request, *args, **kwargs):
        if request.method == "POST":
            username = request.POST['username']
            level = list(User.objects.get(username=username).get_all_permissions())
            return Response({'status': 'ok', 'message': '成功！', 'data': level})
        else:
            return Response({'status': 'error', 'message': '该用户不存在！'})


class UserFormLogin(forms.Form):
    username = forms.CharField(label='用户名', max_length=100)
    password = forms.CharField(label='密码', widget=forms.PasswordInput())
